#!/usr/bin/env python3
# encoding: utf-8
# copyright=zheng panyong
# version: xlsx csv tool 1.0

#need pip3 install pandas openpyxl
#./xlsx2csv.py + path 将输入全路径下指定名字的xlsx转化为csv文件夹(表.csv)


import pandas as pd
import os
import shutil
import sys
     
    
#数据源Excel如果有多个sheet，那么则需要一一遍历输出
def xlsdata_to_csv(xlsx_data,tag_path):
    for K, V in xlsx_data.items():
        tag_file = os.path.join(tag_path, K + '.csv')
        if not V.empty:
            V.to_csv(tag_file, encoding='utf_8_sig', index = False)
    
def dealDir():
    source_path = '' #存放excel文件
    try:
        print("第一个传入的参数为:", sys.argv[1])
        source_path = sys.argv[1]
    except Exception as e:
        print("Input Error:", e)

    dir = os.listdir(source_path)
    for i in dir :
        source_file = os.path.join(source_path, i)
        if source_file.endswith(".xlsx"):
            print("source_file:", source_file)
            xlsx_data = pd.read_excel(source_file, sheet_name=None)

            tag_path = source_file + "_csv_dir"  #输出csv的文件
            if os.path.exists(tag_path):
                shutil.rmtree(tag_path)
                os.mkdir(tag_path)
            else:
                print("need create dir:", tag_path);
                os.mkdir(tag_path)

            xlsdata_to_csv(xlsx_data, tag_path);

def dealXlsx():
    source_path = '' #存放excel文件
    try:
        print("第一个传入的参数为:", sys.argv[1])
        source_path = sys.argv[1]
    except Exception as e:
        print("Input Error:", e)

    source_file = source_path
    if source_file.endswith(".xlsx"):
        print("source_file:", source_file)
        xlsx_data = pd.read_excel(source_file, sheet_name=None)

        tag_path = source_file + "_csv_dir"  #输出csv的文件
        if os.path.exists(tag_path):
            shutil.rmtree(tag_path)
            os.mkdir(tag_path)
        else:
            print("need create dir:", tag_path)
            os.mkdir(tag_path)

        xlsdata_to_csv(xlsx_data, tag_path)

    
if __name__ == '__main__':
    
    dealXlsx()



